package com.atstudying.mall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atstudying.common.utils.HttpUtils;
import com.atstudying.common.utils.PageUtils;
import com.atstudying.common.utils.Query;
import com.atstudying.mall.member.dao.MemberDao;
import com.atstudying.mall.member.dao.MemberLevelDao;
import com.atstudying.mall.member.entity.MemberEntity;
import com.atstudying.mall.member.entity.MemberLevelEntity;
import com.atstudying.mall.member.exception.PhoneExistException;
import com.atstudying.mall.member.exception.UsernameExistException;
import com.atstudying.mall.member.service.MemberService;
import com.atstudying.mall.member.vo.MemberLoginVo;
import com.atstudying.mall.member.vo.MemberRegistVo;
import com.atstudying.mall.member.vo.SocicalUser;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo vo) {

        MemberEntity memberEntity = new MemberEntity();
        MemberDao baseMapper = this.baseMapper;

        //设置默认等级
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(levelEntity.getId());

        //检查用户名和手机号是否唯一；为了让controller可以感知异常，我们使用异常机制（只要有异常就中断，没异常就就往下走
        checkUsernameUnique(vo.getUserName());
        checkPhoneUnique(vo.getPhone());
        memberEntity.setUsername(vo.getUserName());
        memberEntity.setMobile(vo.getPhone());

        //密码要进行加密存储
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());

        memberEntity.setPassword(encode);

        //其他的默认信息

        //保存用户
        baseMapper.insert(memberEntity);

    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {

        MemberDao baseMapper = this.baseMapper;
        Integer mobile = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (mobile > 0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public void checkUsernameUnique(String userName) throws UsernameExistException {
        MemberDao baseMapper = this.baseMapper;
        Integer username = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (username > 0) {
            throw new UsernameExistException();

        }
    }

    @Override
    public MemberEntity login(MemberLoginVo memberLoginVo) {

        String loginacct = memberLoginVo.getLoginacct();
        String password = memberLoginVo.getPassword();
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

        //去数据库查询
        MemberDao baseMapper = this.baseMapper;
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct).or().eq("mobile", loginacct));

        System.out.println(memberEntity);
        if (memberEntity == null) {
            //登录失败
            System.out.println(memberEntity + ".....wwwwwww....................");

            return null;
        } else {

            //判断用户输入密码和数据库查询的密码是否一样
            String password1 = memberEntity.getPassword();
            boolean matches = passwordEncoder.matches(password, password1);
            if (matches) {
                System.out.println(memberEntity + "...........................");

                return memberEntity;
            } else {
                System.out.println(memberEntity + ".....xxxxxxxx......................");

                return null;
            }

        }

    }

    @Override
    public MemberEntity loginOauth2(SocicalUser socicalUser) throws Exception {

        //登录和注册合并逻辑
        String uid = socicalUser.getUid();
        //1：判断当前社交用户是否已经登录过系统
        MemberDao memberDao = this.baseMapper;

        //如果统计出来，当前的uid在数据库中有对应的uid，说明我们注册过
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (memberEntity != null) {

            //这个用户已经注册
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(socicalUser.getAccess_token());
            update.setExpiresIn(socicalUser.getExpires_in());
            update.setSocialUid(socicalUser.getUid());
            memberDao.updateById(update);

            memberEntity.setAccessToken(socicalUser.getAccess_token());
            memberEntity.setExpiresIn(socicalUser.getExpires_in());
            memberEntity.setSocialUid(socicalUser.getUid());

            return memberEntity;
        } else {

            //没有查到当前社交用户对应的记录，我们就需要注册一个
            MemberEntity regist = new MemberEntity();

            //https://api.weibo.com/2/users/show.json?access_token=2.00ZXZCqG0yyJUR39ec702bd5Indy3D
            //&uid=

            //try catch里面就算报错了也没事，关键是最后4行代码
            try {
                Map<String, String> query = new HashMap<>();
                query.put("access_token", socicalUser.getAccess_token());
                query.put("uid", socicalUser.getUid());
                HttpResponse response = HttpUtils.doGet("api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), query);
                if (response.getStatusLine().getStatusCode() == 200) {
                    //查询成功
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(json);
                    //获取微博的昵称，性别。。。。。
                    String name = jsonObject.getString("name");
                    String gender = jsonObject.getString("gender");
                    //..
                    regist.setNickname(name);
                    regist.setGender("m".equals(gender) ? 1 : 0);
                }
            }catch(Exception e){

                }

                //这些代码一定要执行
                regist.setSocialUid(socicalUser.getUid());
                regist.setAccessToken(socicalUser.getAccess_token());
                regist.setExpiresIn(socicalUser.getExpires_in());
                memberDao.insert(regist);

                return regist;
            }
        }


}